﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using RBAC.API.Command.Role;
using System.Transactions;
using Yitter.IdGenerator;

namespace RBAC.API.Handler.Role
{
    public class RoleAddHandler:IRequestHandler<RoleAddCommand,ApiResult<int>>
    {

        private readonly IRepository<RoleModel> roleway;
        private readonly IRepository<RolePermissionModel> rolepermissionway;
        private readonly IRepository<PermissionModel> permissionway;
        private readonly IMapper mapper;
        private readonly ILogger<RoleGetHandler> log;
        private readonly IHttpContextAccessor httpContextAccessor;

        public RoleAddHandler(IRepository<RoleModel> roleway, IRepository<RolePermissionModel> rolepermissionway,
            IRepository<PermissionModel> permissionway, IMapper mapper, ILogger<RoleGetHandler> log, IHttpContextAccessor httpContextAccessor)
        {
            this.roleway = roleway;
            this.rolepermissionway = rolepermissionway;
            this.permissionway = permissionway;
            this.mapper = mapper;
            this.log = log;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        public async Task<ApiResult<int>> Handle(RoleAddCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var i = 0;
            var j = 0;
           // request.CreateTiem = DateTime.Now;  //添加时间
            var role = mapper.Map<RoleModel>(request);
            role.Id = YitIdHelper.NextId();  //雪花主键
            var permissionIds = request.PermissionIds.Split(',')
                                  .Select(s => long.Parse(s.Trim()))
                                  .ToArray();  //将权限主键转化成数字数组
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    i = await roleway.Addway(role);
                    foreach (long item in permissionIds)
                    {
                        RolePermissionModel userrole = new RolePermissionModel()
                        {
                            Id = YitIdHelper.NextId(), //雪花主键
                            PermissionId =  item,
                            RoleId = role.Id,
                        };
                        j += await rolepermissionway.Addway(userrole);
                    }
                    tran.Complete();  //事务回滚
                    if (i > 0 && j > 0)
                    {
                        log.LogInformation($"{httpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(x => x.Type == "UserName")?.Value ?? "默认值"}角色添加成功");
                        res.Message = $"角色添加成功";
                        res.Code = StateCode.OK;
                        res.Data = i + j;
                        return res;
                    }
                    else
                    {
                        res.Message = $"角色添加失败";
                        res.Code = StateCode.Fail;
                        return res;
                    }


                }
                catch (Exception ex)
                {
                    log.LogError($"{httpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(x => x.Type == "UserName")?.Value ?? "默认值"}角色添加时发生异常{ex.Message}");
                    throw;
                }
            }
        }
    }
}
